package cn.wolfcode.luowowo.website.web.resolver;

import cn.wolfcode.luowowo.cache.service.IUserInfoRedisService;
import cn.wolfcode.luowowo.member.domain.UserInfo;
import cn.wolfcode.luowowo.website.util.CookieUtil;
import cn.wolfcode.luowowo.website.web.annotation.UserParam;
import com.alibaba.dubbo.config.annotation.Reference;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 自定义参数解析器
 * : 将当前登录用户对象， 注入到请求映射方法中声明的UserInfo userInfo变量中
 */
public class UserInfoArgumentResolver implements HandlerMethodArgumentResolver {
    @Reference
    private IUserInfoRedisService userInfoRedisService;
    //表示当前参数解析器支持解析类型
    //此处支持的UserInfo 类型
    //methodParameter 是请求映射方法参数抽象-  info(UserInfo userInfo)
    @Override
    public boolean supportsParameter(MethodParameter methodParameter) {
        return methodParameter.getParameterType() == UserInfo.class
                && methodParameter.hasParameterAnnotation(UserParam.class) ;
    }
    //如何解析支持类型
    //如果将当前登录用户对象注入 请求映射方法UserInfo 变量中
    //必须是：supportsParameter 返回true 才执行
    @Override
    public Object resolveArgument(MethodParameter methodParameter, ModelAndViewContainer modelAndViewContainer,
                                  NativeWebRequest nativeWebRequest, WebDataBinderFactory webDataBinderFactory) throws Exception {
        //获取请求对象
        HttpServletRequest req = nativeWebRequest
                .getNativeRequest(HttpServletRequest.class);
        HttpServletResponse resp = nativeWebRequest
                .getNativeResponse(HttpServletResponse.class);
        //获取token
        String token = CookieUtil.getToken(req, resp);
        //获取当前登录用户信息
        UserInfo user = userInfoRedisService.getUserByToken(token);
        return user;
    }
}
